package offerbook.Code25_pathInBT;

import utils.TreeNode;
import utils.TreeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 输出二叉树从根节点开始的所有路径,
 * 注：路径满足以根节点开始，以叶子节点结束
 * @date 2020/3/9 18:48
 */
public class Code01_FindAllPath1 {
    public static List<List<Integer>> findAllPath(TreeNode treeNode) {
        List<List<Integer>> totalPath = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        if (treeNode == null) {
            return totalPath;
        }
        preInOder(treeNode, totalPath,path);
        return totalPath;
    }

    private static void preInOder(TreeNode root, List<List<Integer>> totalPath, List<Integer> path) {
        if(root == null){
            return;
        }
        //前序遍历要处理的当前节点,先添加当前节点
        path.add(root.val);
        //如果是叶子节点，那么把当前路径加入,
        if (root.left == null && root.right == null) {
            //要开启新的点
            totalPath.add(new ArrayList<>(path));
            //注意这里不要加return，不然导致当前叶子节点无法被及时删除。并且如果在这里删除节点，那么只能删除叶子节点，会出错
        }else {
            preInOder(root.left, totalPath,path);
            preInOder(root.right, totalPath,path);
        }
        //返回上一级，要删除当前节点
        path.remove(path.size() - 1);
    }
    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(12);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(7);
        TreeUtil.printTree(root);
        List<List<Integer>> totalPath = findAllPath(root);
        System.out.println(totalPath);
    }
}
